package com.pensar.tabkids.student.festivalsstudentapp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.pensar.tabkids.student.common.StudentAppActivity;
import com.pensar.tabkids.student.util.CommonUtil;
import com.pensar.tabkids.student.util.TabkidsResourceUtil;

public class StartActivity extends StudentAppActivity {
	GridView gridview;
	ListView hidenlistview, foundlistview;
	private TextViewAdapter Gadapter;
	Point startpoint, Endpoint;
	HidenWordList hidenwordAdapter;
	String selected_Option, selected_category, chars, currentWord;
	public static final String selected_option = "option";
	public static final int default_num = 20;
	int id = 0, selected_festivals_no, random_num_v_col, random_num_h_col,
			random_num_v_row, random_num_h_row, row = default_num,
			colomn = default_num, positionOndown, downI, downJ, Array_index,
			nums_index_col, nums_index_row, count, ran_row_colomn;
	JSONArray arlist;
	ArrayList<String> array, textviewList, gridItem, hidenWord, foundWord;
	ArrayList<Integer> indexId, nums_h_col, nums_v_row, touchWord,
			uniqueposition, wl;
	String[] values;
	boolean flag, fixcodinate = false, screenshot, random_row_colomn;
	float currentXPositionOndown, currentYPositionOndown;
	int size_h, size_v, prow, repeatTime, pcol, totalWordInhidenword,startPosition = 0;;
	private Random random = new Random();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		getIntent().putExtra("activityId", 149);
		setResourceClass(R.class);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gridview = (GridView) findViewById(R.id.gridView1);

		hidenlistview = (ListView) findViewById(R.id.hidenwordlist);
		foundlistview = (ListView) findViewById(R.id.foundwordlist);
		((LinearLayout) findViewById(R.id.linearlayout))
				.setVisibility(View.GONE);
		((GridView) findViewById(R.id.gridView1)).setVisibility(View.GONE);

		((LinearLayout) findViewById(R.id.conpletionLinearlayout))
				.setVisibility(View.GONE);
		;
		assignMethod();
		// create arraylist from json

	}

	private void assignMethod() {
		// TODO Auto-generated method stub
		array = new ArrayList<String>();
		gridItem = new ArrayList<String>();
		hidenWord = new ArrayList<String>();
		foundWord = new ArrayList<String>();
		indexId = new ArrayList<Integer>();
		nums_h_col = new ArrayList<Integer>();
		nums_v_row = new ArrayList<Integer>();
		uniqueposition = new ArrayList<Integer>();
		touchWord = new ArrayList<Integer>();
	}

	@SuppressLint("NewApi")
	private void allArrayClear() {
		gridItem.clear();
		array.clear();
		hidenWord.clear();
		foundWord.clear();
		indexId.clear();
		nums_h_col.clear();
		nums_v_row.clear();
		uniqueposition.clear();
		touchWord.clear();

	}

	// for list

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public void autoAssignNextProblem() {
		// TODO Auto-generated method stub

	}

	@Override
	public void autoClearCurrentProblem() {
		// TODO Auto-generated method stub

	}

	@Override
	public void handleAssignFromTeacher(JSONObject extraInfo) {
		screenshot = true;
		((LinearLayout) findViewById(R.id.conpletionLinearlayout))
				.setVisibility(View.GONE);
		((LinearLayout) findViewById(R.id.linearlayout))
				.setVisibility(View.GONE);

		// TODO Auto-generated method stub
		if (!gridItem.isEmpty()) {
			allArrayClear();
		}
		if (!array.isEmpty() || array.isEmpty()) {
			count = 0;
			JSONObject CategoryListObject = TabkidsResourceUtil
					.loadJsonFromFile("149.json");
			Log.d("tag", "" + CategoryListObject);
			JSONArray categoryListArray = null;

			try {
				categoryListArray = CategoryListObject
						.getJSONArray("Festivals");
				for (int i = 0; i < categoryListArray.length(); i++) {
					array.add(categoryListArray.getString(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			Log.d("array", "" + array);
		}
		try {
			selected_Option = extraInfo.getString(selected_option);
			selected_festivals_no = Integer.parseInt(extraInfo
					.getString("select_festivals_no"));
			selected_category = extraInfo.getString("category_name");
			Log.d("selected festival", "" + selected_festivals_no);
			Log.d("select", selected_Option);
			if (selected_Option.equals("grid")) {
				if (selected_category.equals("withname")) {
					((LinearLayout) findViewById(R.id.linearlayout))
							.setVisibility(View.VISIBLE);
				}

				((GridView) findViewById(R.id.gridView1))
						.setVisibility(View.VISIBLE);
				for (int k = 0; k < selected_festivals_no; k++) {
					Array_index = random.nextInt(array.size());

					hidenWord.add(array.get(Array_index));
					array.remove(Array_index);

				}
				totalWordInhidenword = hidenWord.size();
				Log.d("list", "" + hidenWord);
				Log.d("gridsize", "" + colsSize());
				if (colsSize() > 9) {
					size_h = colsSize() + 6;
				} else {
					size_h = colsSize() + 3;
				}

				if (size_h < 11) {
					size_v = size_h;
				} else {
					size_v = 11;
				}

				randomnum();
				display();

				touchOnGrid();

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list) {

		// Store unique items in result.
		ArrayList<Integer> result = new ArrayList<Integer>();

		// Record encountered Strings in HashSet.
		HashSet<Integer> set = new HashSet<Integer>();

		// Loop over argument list.
		for (Integer item : list) {

			// If String is not in set, add it to the list and the set.
			if (!set.contains(item)) {
				result.add(item);
				set.add(item);
			}
		}
		return result;
	}

	private void randomnum() {
		// TODO Auto-generated method stub
		for (int i = 0; i < size_h; i++) {
			nums_h_col.add(i);
			if (i < size_v) {
				nums_v_row.add(i);
			}

		}

	}

	private void display() {
		// TODO Auto-generated method stub
		// create Table

		// create arraylist for grid
		for (int i = 0; i < size_h * size_v; i++) {
			gridItem.add("Z");
		}

		for (int k = 0; k < selected_festivals_no; k++) {
			id = 0;

			chars = hidenWord.get(k);
			Log.d("total length col", "" + nums_h_col.size());
			Log.d("total length row", "" + nums_v_row.size());
			ran_row_colomn = random.nextInt(2);

			if (ran_row_colomn == 1) {
				random_row_colomn = true;
			} else {
				random_row_colomn = false;
			}
			if (nums_h_col.size() != 0) {
				nums_index_col = random.nextInt(nums_h_col.size());
				random_num_h_col = nums_h_col.get(nums_index_col);
			}
			if (nums_v_row.size() != 0) {
				nums_index_row = random.nextInt(nums_v_row.size());
				random_num_v_row = nums_v_row.get(nums_index_row);

				if (size_h != chars.length()) {
					random_num_h_row = random.nextInt(size_h - chars.length());
				} else {
					random_num_h_row = 0;
				}

				if (size_v != chars.length()) {
					random_num_v_col = random.nextInt(size_v - chars.length());
				} else {
					random_num_v_col = 0;
				}
			}

			boolean repeat = false;
			do {
				repeat = false;
				if (nums_v_row.size() == 0) {
					random_row_colomn = false;
				}
				if (nums_h_col.size() == 0) {
					random_row_colomn = true;
				}
				// check don't assign already value
				wl = new ArrayList<Integer>();
				currentWord = hidenWord.get(k);
				// for row
				prow = random_num_h_row + size_h * random_num_v_row;
				pcol = random_num_h_col + size_h * random_num_v_col;
				Log.d("row run", "" + random_row_colomn);
				if (random_row_colomn == true) {

					wl.add(prow);
					for (int wordsize = 0; wordsize < currentWord.length(); wordsize++) {
						Log.d("gridposition = ", "" + prow);
						if (indexId.contains(wl.get(wordsize))) {
							Log.d("content match", "content match");

							try {
								if (size_h != chars.length()) {
									random_num_h_row = random.nextInt(size_h
											- chars.length());
								} else {
									random_num_h_row = 0;
								}
							} catch (Exception e) {
								// TODO: handle exception
								Log.d("repeat time row illigleArgumentException",
										"illigleArgumentException value = "
												+ random_num_h_row);
								random_num_h_row = 0;
							}
							if (nums_v_row.size() != 0) {
								nums_index_row = random.nextInt(nums_v_row
										.size());
								random_num_v_row = nums_v_row
										.get(nums_index_row);
								random_row_colomn = false;
							}
							prow = random_num_h_row + size_h * random_num_v_row;
							repeat = true;

							wl.clear();
							break;
						} else {
							Log.d("content don't match", "content don't match");
							prow++;
							wl.add(prow);
						}
					}

					wl.clear();
					if (repeat == true) {
						nums_v_row.remove(nums_index_row);
					}
					Log.d("row nums v", "" + nums_v_row.size());

				} else {

					wl.add(pcol);
					for (int wordsize = 0; wordsize < currentWord.length(); wordsize++) {
						Log.d("gridposition = ", "" + pcol);
						if (indexId.contains(wl.get(wordsize))) {
							Log.d("content match", "content match");
							try {
								if (size_v != chars.length()) {
									random_num_v_col = random.nextInt(size_v
											- chars.length());
								} else {
									random_num_v_col = 0;
								}

							} catch (Exception e) {
								// TODO: handle exception
								Log.d("repeat time col illigleArgumentException",
										"illigleArgumentException value = "
												+ random_num_v_col);

								random_num_v_col = 0;
							}
							if (nums_h_col.size() != 0) {
								nums_index_col = random.nextInt(nums_h_col
										.size());
								random_num_h_col = nums_h_col
										.get(nums_index_col);
								random_row_colomn = true;
							}
							pcol = random_num_h_col + size_h * random_num_v_col;
							repeat = true;

							wl.clear();

							break;
						} else {
							Log.d("content don't match", "content don't match");
							pcol = pcol + size_h;
							wl.add(pcol);
						}
					}
					wl.clear();
					if (repeat == true) {
						nums_h_col.remove(nums_index_col);
					}
				}
				Log.d("column nums h", "" + nums_h_col.size());
			} while (repeat == true);

			// create arraylist for grid
			for (int i = 0; i < size_v; i++) {
				for (int j = 0; j < size_h; j++) {
					if (random_row_colomn == true) {
						if (i == random_num_v_row && j == random_num_h_row
								|| row < chars.length()) {
							if (j == random_num_h_row) {
								row = 0;
							}
							StringBuilder sb2 = new StringBuilder();
							char s = chars.charAt(row);
							sb2.append(s);
							String s1 = sb2.toString();
							if (row == 0) {
								System.out.println("word row= " + s1);
								System.out.println("horizontal row ="
										+ random_num_h_row);
								System.out.println("vertical row = "
										+ random_num_v_row);
							}
							gridItem.set(id, s1);
							indexId.add(id);
							id++;
						} else {
							id++;
						}
						if (row >= 0) {
							row += 1;
						}
					} else {
						if ((i == random_num_v_col || colomn < chars.length())
								&& j == random_num_h_col) {
							if (i == random_num_v_col) {
								colomn = 0;
							}
							StringBuilder sb2 = new StringBuilder();
							char s = chars.charAt(colomn);
							sb2.append(s);
							String s1 = sb2.toString();
							if (colomn == 0) {
								System.out.println("word = " + s1);
								System.out.println("horizontal = "
										+ random_num_h_col);
								System.out.println("vertical column = "
										+ random_num_v_col);
							}
							gridItem.set(id, s1);
							indexId.add(id);
							id++;
						} else {
							id++;
						}
					}
				}
				if (colomn >= 0) {
					colomn += 1;
				}
			}
			/* System.out.println("My Index Id : " + indexId); */

		}
		id = 0;
		// for assigning random values
		for (int i = 0; i < size_v * size_h; i++) {
			if (gridItem.get(i) == "Z") {
				char[] chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
				StringBuilder sb1 = new StringBuilder();
				char c1 = chars1[random.nextInt(chars1.length)];
				sb1.append(c1);
				String random_string = sb1.toString();
				gridItem.set(id, random_string);
				id++;
			} else {
				id++;
			}
		}

	}

	@Override
	public JSONObject getCompletionCountJson() {
		// TODO Auto-generated method stub
		return CommonUtil.getCompletionCountJson(1, 0);
	}

	@Override
	public boolean isCurrentTaskCompleted() {
		boolean isComplete = false;
		if (count == totalWordInhidenword) {
			isComplete = true;
		}
		return isComplete;
	}

	@Override
	public boolean autoStopCurrentTask() {

		// TODO Auto-generated method stub
		return false;
	}

	private void touchOnGrid() {
		// TODO Auto-generated method stub
		hidenwordAdapter = new HidenWordList(this, R.layout.hidenlist,
				hidenWord);
		hidenlistview.setAdapter(hidenwordAdapter);

		gridview.setNumColumns(size_h);

		Gadapter = new TextViewAdapter(this, gridItem);
		gridview.setAdapter(Gadapter);

		gridview.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent me) {
				if (screenshot == true) {
					screenshot = false;
					takeScreenshot(R.id.parentloyout, true, true);
				}
				
				TextView tv;
				int action = me.getActionMasked();
				float currentXPosition = me.getX();
				float currentYPosition = me.getY();
				int position = gridview.pointToPosition((int) currentXPosition,
						(int) currentYPosition);

				switch (action) {
				case MotionEvent.ACTION_DOWN:
					

					currentXPositionOndown = me.getX();
					currentYPositionOndown = me.getY();
					positionOndown = gridview.pointToPosition(
							(int) currentXPositionOndown,
							(int) currentYPositionOndown);
				 startPosition=positionOndown;
					 Log.d("startPosition", ""+startPosition); 
					break;
				case MotionEvent.ACTION_MOVE:
					try {
						
						if (position >= 0) {
							String s = (String) gridview
									.getItemAtPosition(position);

							downI = (startPosition - (startPosition % size_h))
									/ size_h;
							downJ = startPosition % size_h;

							
							if ((position - (position % size_h)) / size_h == downI ) {

								// Remove duplicates from ArrayList of Strings.

								  Log.d("startPosition", ""+startPosition);
								  Log.d("position", ""+position);
								 

								if (startPosition < position) {
									Iterator<Integer> it = uniqueposition.iterator();
									while (it.hasNext()) {
										Integer positionList = (Integer) it.next();
										// System.out.println("My Posion");
										tv = (TextView) gridview.getChildAt(positionList);
										if (tv.getCurrentTextColor() != Color.DKGRAY) {
											tv.setBackgroundColor(Color
													.parseColor("#ffe0b2"));
										} else {
											tv.setBackgroundColor(Color.GREEN);

										}
										touchWord.clear();
									}

									uniqueposition.clear();
									while (startPosition <= position) {
										tv = (TextView) gridview
												.getChildAt(startPosition);
										tv.setBackgroundColor(Color.BLUE);
										touchWord.add(startPosition);
										uniqueposition = removeDuplicates(touchWord);
										startPosition++;
										
									}
									startPosition=positionOndown;
								} else {
									Iterator<Integer> it = uniqueposition.iterator();
									while (it.hasNext()) {
										Integer positionList = (Integer) it.next();
										// System.out.println("My Posion");
										tv = (TextView) gridview.getChildAt(positionList);
										if (tv.getCurrentTextColor() != Color.DKGRAY) {
											tv.setBackgroundColor(Color
													.parseColor("#ffe0b2"));
										} else {
											tv.setBackgroundColor(Color.GREEN);

										}
										touchWord.clear();
									}

									uniqueposition.clear();
									while (startPosition >= position) {
										tv = (TextView) gridview
												.getChildAt(startPosition);
										tv.setBackgroundColor(Color.BLUE);
										touchWord.add(startPosition);
										uniqueposition = removeDuplicates(touchWord);
										startPosition--;
										
									}
									startPosition=positionOndown;
								}

							}else{
								
							if (downJ == position % size_h) {

								
								if (startPosition < position) {
									Iterator<Integer> it = uniqueposition.iterator();
									while (it.hasNext()) {
										Integer positionList = (Integer) it.next();
										// System.out.println("My Posion");
										tv = (TextView) gridview.getChildAt(positionList);
										if (tv.getCurrentTextColor() != Color.DKGRAY) {
											tv.setBackgroundColor(Color
													.parseColor("#ffe0b2"));
										} else {
											tv.setBackgroundColor(Color.GREEN);

										}
										touchWord.clear();
									}

									uniqueposition.clear();
									while (startPosition <= position) {
										tv = (TextView) gridview
												.getChildAt(startPosition);
										tv.setBackgroundColor(Color.BLUE);
										touchWord.add(startPosition);
										uniqueposition = removeDuplicates(touchWord);
										startPosition += size_h;
										
									}
									startPosition=positionOndown;
								} else {
									Iterator<Integer> it = uniqueposition.iterator();
									while (it.hasNext()) {
										Integer positionList = (Integer) it.next();
										// System.out.println("My Posion");
										tv = (TextView) gridview.getChildAt(positionList);
										if (tv.getCurrentTextColor() != Color.DKGRAY) {
											tv.setBackgroundColor(Color
													.parseColor("#ffe0b2"));
										} else {
											tv.setBackgroundColor(Color.GREEN);

										}
										touchWord.clear();
									}

									uniqueposition.clear();
									while (startPosition >= position) {
										tv = (TextView) gridview
												.getChildAt(startPosition);
										tv.setBackgroundColor(Color.BLUE);
										touchWord.add(startPosition);
										uniqueposition = removeDuplicates(touchWord);
										startPosition -= size_h;
									}
									startPosition=positionOndown;
								}

							}
							}

						}
						

						// Log.d("color", ""+tv.getCurrentTextColor());

					} catch (Exception e) {
						// TODO: handle exception
						Log.i("exception", "grid over touch");
					}
					break;
				case MotionEvent.ACTION_UP:

					/* Log.d("uniqueposition", ""+uniqueposition); */

					Iterator<Integer> itr = uniqueposition.iterator();
					String wordMatch = "";
					while (itr.hasNext()) {
						Integer addstring = (Integer) itr.next();
						tv = (TextView) gridview.getChildAt(addstring);
						wordMatch += (String) tv.getText();
					}
					Log.d("wordmatch", wordMatch);

					if (hidenWord.contains(wordMatch)) {

						Iterator<Integer> it = uniqueposition.iterator();
						while (it.hasNext()) {
							Integer positionList = (Integer) it.next();
							// System.out.println("selected Posion");
							tv = (TextView) gridview.getChildAt(positionList);
							tv.setBackgroundColor(Color.GREEN);
							tv.setTextColor(Color.DKGRAY);
							touchWord.clear();
						}
						Log.d("count", "" + count);
						count++;

						/* takeScreenshot(R.id.parentloyout, true, true); */
						if (count == totalWordInhidenword) {
							takeScreenshot(R.id.parentloyout, false, true);
							((LinearLayout) findViewById(R.id.linearlayout))
									.setVisibility(View.GONE);
							((GridView) findViewById(R.id.gridView1))
									.setVisibility(View.GONE);
							((LinearLayout) findViewById(R.id.conpletionLinearlayout))
									.setVisibility(View.VISIBLE);
							;

						}
						hidenWord.remove(wordMatch);
					} else {
						/* takeScreenshot(R.id.parentloyout, true, false); */
						Log.d("print", "" + uniqueposition);
						Iterator<Integer> it = uniqueposition.iterator();
						while (it.hasNext()) {
							Integer positionList = (Integer) it.next();
							// System.out.println("My Posion");
							tv = (TextView) gridview.getChildAt(positionList);
							if (tv.getCurrentTextColor() != Color.DKGRAY) {
								tv.setBackgroundColor(Color
										.parseColor("#ffe0b2"));
							} else {
								tv.setBackgroundColor(Color.GREEN);

							}
							touchWord.clear();
						}

					}
					uniqueposition.clear();
					break;

				default:
					break;
				}
				// Change the color of the key pressed

				return true;
			}

		});

	}

	private int colsSize() {
		int length = 0, columnsSize = 0;
		double dbcolumnsSize = 0;
		for (int i = 0; i < hidenWord.size(); i++) {
			length = length + hidenWord.get(i).length();
		}
		;

		int maxSize = 0;

		for (int j = 0; j < hidenWord.size(); j++) {
			if (maxSize < (hidenWord.get(j)).length()) {
				maxSize = (hidenWord.get(j)).length();
			}
		}
		if (maxSize * maxSize < length) {
			dbcolumnsSize = (Math.sqrt(length)) + 3;
			columnsSize = (int) dbcolumnsSize;
		} else {
			columnsSize = maxSize;
		}

		Log.d("length", "" + columnsSize);
		Log.d("length", "" + length);
		return columnsSize;

	}

	private void selectionPaint(Point pointStart, Point pointEnd, Color color) {
		Point delta = Selection.getDeltas(pointStart, pointEnd);

		if (delta == null) {
			return;
		}
		Point point = new Point();
		point.x = pointStart.x;
		point.y = pointStart.y;
		int currentPosition = gridview.pointToPosition(point.x, point.y);
		TextView ctv = (TextView) gridview.getChildAt(currentPosition);
		if (!Selection.isValidPoint(point, size_v * size_h)) {
			throw new NullPointerException("point: " + point.x + "," + point.y
					+ "; delta: " + delta.x + "," + delta.y + "; length: "
					+ (size_v * size_h));
		}
		ctv.setBackgroundColor(Color.RED);
		do {
			point.x += delta.x;
			point.y += delta.y;
			if (!point.equals(pointStart)
					&& Selection.isValidPoint(point, size_v * size_h)) {
				ctv.setBackgroundColor(Color.RED);
			}
		} while (!point.equals(pointEnd)
				&& Selection.isValidPoint(point, size_v * size_h));
	}

}
